﻿using AutoMapper;
using MediatR;
using BaseData.CommonLib.Models;
using BaseData.DomainLib.AggregatesModel.MaterialCategoryAggregate;
using Swimj.CommonLib.Base;

namespace BaseData.ApplicationLib.Commands
{
    public class CreateMaterialCategoryCommand : MaterialCategoryEditRequestDto,
        IRequest<Result<MaterialCategoryInfoResponseDto>>
    {
    }

    public class CreateMaterialCategoryCommandHandler : IRequestHandler<CreateMaterialCategoryCommand,
        Result<MaterialCategoryInfoResponseDto>>
    {
        private readonly IMaterialCategoryRepository _materialCategoryRepository;
        private readonly IMapper _mapper;

        public CreateMaterialCategoryCommandHandler(IMaterialCategoryRepository materialCategoryRepository,
            IMapper mapper)
        {
            _materialCategoryRepository = materialCategoryRepository;
            _mapper = mapper;
        }

        public async Task<Result<MaterialCategoryInfoResponseDto>> Handle(CreateMaterialCategoryCommand request,
            CancellationToken cancellationToken)
        {
            var materialCategory = new MaterialCategory(request.Code, request.Name, request.ParentId,
                request.Sort, request.Description);
            _materialCategoryRepository.Add(materialCategory);

            await _materialCategoryRepository.UnitOfWork.SaveEntitiesAsync(cancellationToken);

            return await Result<MaterialCategoryInfoResponseDto>.SuccessAsync(
                _mapper.Map<MaterialCategoryInfoResponseDto>(materialCategory));
        }
    }
}